global class DistributionPointScheduler implements schedulable {
    /*
        select ownerid,count(actual__c) aaa from TradeDashboardDetails__c 
        where CriticalEnabler__c='Distribution Point'  group by ownerid
    */
    global void execute(schedulablecontext sc)
    {
       RunDistributionPoint();
       SetSalesTarget();
    }
    public void RunDistributionPoint()
    {
         List<TradeDashboardDetails__c> ssyList=new List<TradeDashboardDetails__c>();
        //ScoreStandard__c score=ScoreStandard__c.getValues('Distribution Point');
       // List<Id> OwnerIdList=new List<Id>();
        Date DToday=Date.newInstance(Date.today().year(),Date.today().month(),1);
        Map<String,TradeDashboardDetails__c> UpsertMapList=new Map<String,TradeDashboardDetails__c>();
       // Map<String,TradeDashboardDetails__c> mapList2=new Map<String,TradeDashboardDetails__c>();
        String keyString; 
        DateTime dt;
        Date d;
        
        List<In_Store_Visit__c> AllInStoreVisitList=[Select Id,RoutingPlanAndVisit__r.OwnerId,OutletName_del__c,Start_Time__c ,
                                                InventoryDisplayPriceGreaterThan0__c,StartDate__c, OwnerId__c,HasRunDistributionPoint__c
                                                From In_Store_Visit__c Where HasRunDistributionPoint__c =: FALSE 
                                                and InventoryDisplayPriceGreaterThan0__c>0 limit 5000];
        
        for(In_Store_Visit__c st:AllInStoreVisitList)  
        {
            st.HasRunDistributionPoint__c=true;
            dt=st.Start_Time__c;
            d=Date.newInstance(dt.year(),dt.month(),1);
            keyString=String.valueOf(st.OutletName_del__c)+String.valueOf(st.RoutingPlanAndVisit__r.OwnerId)+String.valueOf(d)+'Distribution Point';
            TradeDashboardDetails__c sae=new TradeDashboardDetails__c();
            sae.CriticalEnabler__c='Distribution Point';
            sae.Outlet__c=st.OutletName_del__c;
            sae.ScoreStandard__c=ScoreStandard__c.getValues('Distribution Point').Standard__c;
            sae.Actual__c=1;
            sae.OwnerId=st.RoutingPlanAndVisit__r.OwnerId;
            sae.TSR__c=st.RoutingPlanAndVisit__r.OwnerId;
            sae.SalesMonth__c=d;
            sae.TSR__c=st.RoutingPlanAndVisit__r.OwnerId;
            sae.PrimaryKeyId__c=KeyString;
            UpsertMapList.put(KeyString,sae);
            
        }
        if(UpsertMapList.size()>0)
            upsert UpsertMapList.values() PrimaryKeyId__c;
            
      //以下是对salestarget、LastActual的逻辑处理
      //查出上个月拜访的店数
     /*      List<AggregateResult> ListCountLastActual=[select OwnerId,count(actual__c) LastA from TradeDashboardDetails__c where
                                                      CriticalEnabler__c='Distribution Point' 
                                                      and SalesMonth__c=LAST_MONTH
                                                      group by ownerid];
                                                      
           
            List<AggregateResult> ListCountThisMonth=[select ownerid  from TradeDashboardDetails__c 
                                                   where CriticalEnabler__c='Distribution Point'  
                                                   and SalesMonth__c=THIS_MONTH group by ownerid];
            
            for(AggregateResult tr:ListCountThisMonth)
            {
                OwnerIdList.add((String)tr.get('ownerid'));
            }
            
            //取出salestarget                                     
            List<Sales_Target__c> targetList=[select MaxValue__c,NextSales__c,Sales_Target_Type__c 
                                              from Sales_Target__c 
                                              where NextSales__c in:OwnerIdList and Month__c=:String.valueOf(DToday.Month())
                                              and Year__c =:String.valueOf(DToday.Year()) 
                                              and Sales_Target_Type__c='Distributed Outlet Number'];
            
            if(targetList!=NULL && targetList.size()>0)//写入SalesTarget到map中
             {
                String StKey='';
                 for(Sales_Target__c i:targetList)
                 {
                   
                     StKey=String.valueOf(DToday)+i.NextSales__c+'SalesTarget'+'Distribution Point';
                     TradeDashboardDetails__c sae=new TradeDashboardDetails__c();
                     sae.CriticalEnabler__c='Distribution Point';
                     sae.OwnerId=i.NextSales__c;
                     sae.Target__c=i.MaxValue__c;
                     sae.SalesMonth__c=DToday;
                     sae.PrimaryKeyId__c=StKey;
                     sae.LastMonthActual__c=0;
                     mapList2.put(StKey,sae);
                 }
             } 
            
            if(ListCountLastActual!=NULL)
             {
                String StKey='';
                 for(AggregateResult t:ListCountLastActual)
                 {
                    StKey=String.valueOf(DToday)+t.get('OwnerId')+'SalesTarget'+'Distribution Point';
                    TradeDashboardDetails__c sae=mapList2.get(StKey);
                    if(sae!=NULL)
                    {
                      sae.LastMonthActual__c=(Integer)t.get('LastA');
                      mapList2.put(StKey,sae);
                    }
                    else
                    {
                        sae=new TradeDashboardDetails__c();
                        sae.CriticalEnabler__c='Distribution Point';
                        sae.OwnerId=(String)t.get('OwnerId');
                        sae.Target__c=0;
                        sae.SalesMonth__c=DToday;
                        sae.LastMonthActual__c=(Integer)t.get('LastA');
                        sae.PrimaryKeyId__c=StKey;
                        mapList2.put(StKey,sae);
                    }
                 }
             }
            if(mapList2.size()>0)
                upsert mapList2.values() PrimaryKeyId__c;*/
                
            update AllInStoreVisitList;
    }
    
   public void SetSalesTarget()
   {
   		Date DToday=Date.newInstance(Date.today().year(),Date.today().month(),1);
   		Map<String,TradeDashboardDetails__c> sTargetMapList=new Map<String,TradeDashboardDetails__c>();
   		Map<String,SSYActivityExecutionTracking__c> sTargetSSYMapList=new Map<String,SSYActivityExecutionTracking__c>();
   		
   		List<Sales_Target__c> stList=[select MaxValue__c,NextSales__c,Sales_Target_Type__c 
         							  from Sales_Target__c 
         	  						  where Month__c=:String.valueOf(DToday.Month())
               						  and Year__c=:String.valueOf(DToday.Year())
               						  and TSRIsActive__c='1'
               						  and (Sales_Target_Type__c='Main-Shelf Standard Display Outlet Number'
               							   or Sales_Target_Type__c='Distributed Outlet Number'
               							   or Sales_Target_Type__c='SSY Activity Outlet Number')];
               
         String StKey='',ssykey='';
         for(Sales_Target__c i:stList)
         {
           //处理TradeDashboardDetails__c表的SalesTarget
             StKey=String.valueOf(DToday)+i.NextSales__c+'SalesTarget'+i.Sales_Target_Type__c;
             TradeDashboardDetails__c sae=new TradeDashboardDetails__c();
             if(i.Sales_Target_Type__c=='Main-Shelf Standard Display Outlet Number')
             	sae.CriticalEnabler__c='Main Shelf Display Achievement';
             else if(i.Sales_Target_Type__c=='Distributed Outlet Number')
             	sae.CriticalEnabler__c='Distribution Point';
             else if(i.Sales_Target_Type__c=='SSY Activity Outlet Number')
             	sae.CriticalEnabler__c='SSY Activity Achievement';
             
             sae.OwnerId=i.NextSales__c;
             sae.Target__c=i.MaxValue__c;
             sae.SalesMonth__c=DToday;
             sae.PrimaryKeyId__c=StKey;
             sTargetMapList.put(StKey,sae);
             
             //处理SSYActivityExecutionTracking__c表的SalesTarget
             if(i.Sales_Target_Type__c=='SSY Activity Outlet Number')
             {
             	ssykey=String.valueOf(DToday)+i.NextSales__c+'SSYActivity'+'SalesTarget';
                SSYActivityExecutionTracking__c ssy=new SSYActivityExecutionTracking__c();
                ssy.ExecutedSSY__c=0;
                ssy.SSYTarget__c=i.MaxValue__c;
                ssy.SalesMonth__c=DToday;
                ssy.OwnerId=i.NextSales__c;
                ssy.TSR__c=i.NextSales__c;
                ssy.PrimaryKeyId__c=ssykey;
                sTargetSSYMapList.put(ssykey,ssy);
             }
         }
                    
        if(sTargetMapList.size()>0)
        	upsert sTargetMapList.values() PrimaryKeyId__c;
        if(sTargetSSYMapList.size()>0)
        	upsert sTargetSSYMapList.values() PrimaryKeyId__c;
        	
   }
    
}